<template>
  <div class="chat_container">
    <div class="activity">
      <img src="@/assets/icons/live-detail/speaker.webp" />
      <span class="txt">任何群、广告均为诈骗，违规者封号处理 </span>
    </div>
    <div class="message-container" ref="messageContainer">
      <div class="vip-list">
        <div class="vip-item" v-for="(res, index) in messageList" :key="res.id">
          <img src="@/assets/icons/live-detail/chat-level0.webp" alt="VIP1" class="vip-badge" />
          <div>
            <span class="nickname">{{ res?.nickname }}:</span>
            <span class="text">{{ res?.content }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="join-list">
      <span class="nickname">{{ joinList.data.nickname }}</span>
      <span class="text">{{ joinList.data.content }}</span>
    </div>
    <div class="comment-section">
      <!-- <div class="comment-tools">
              <span class="tool-text">文字</span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
            </div> -->
      <div class="comment-input">
        <div class="isNotLogin" v-if="!isLogin">
          <span class="login_btn" @click="login">登陆</span>
          <span>参与与主播一起聊球</span>
        </div>
        <div class="isLogin" v-if="isLogin">
          <input type="text" placeholder="说点有爱的评论~" v-model="msg" @keyup.enter="sendMsg" />
          <button class="send-button" @click="sendMsg">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { defineProps, ref, reactive, watch, defineEmits, nextTick } from 'vue'
import { getDQRongImLibToken } from '@/api/user'
import * as RongIMLib from '@rongcloud/imlib-next'
import { useRouter } from 'vue-router'
import { userStore } from '@/stores/user'
import { AppConfigStore } from '@/stores/app'
import { message } from 'ant-design-vue'
const userState = userStore()
const appConfigState = AppConfigStore()
const router = useRouter()
const isLogin = ref(false)
const msg = ref('')
// const props = defineProps(['chatRoomId', 'selfMsg'])

const props = defineProps(['chatId'])
const messageContainer = ref(null)
const im = RongIMLib.init({ appkey: 'tdrvipksty5k5' })
const messageList = ref([])
const joinList = reactive({
  data: {}
})
// console.log(im, 'im')
const chatRoomIdRef = ref('')
if (userState?.token) {
  isLogin.value = true
  console.log(userState?.userInfo, 'userState?.userInfo?')
} else {
  isLogin.value = false
}

const initRongIMLib = () => {
  getDQRongImLibToken()
    .then((val) => {
      console.log(val, 'res')
      RongIMLib.connect(val.data.url)
        .then((res) => {
          if (res.code === RongIMLib.ErrorCode.SUCCESS) {
            console.log('链接成功, 链接用户 id 为: ', res.data.userId)
            RongIMLib.joinExistChatRoom(chatRoomIdRef.value.toString(), {
              count: 50
            })
              .then((res) => {
                // 加入聊天室成功
                const { code, data } = res
                if (code === RongIMLib.ErrorCode.SUCCESS) {
                  console.log(code, data)
                } else {
                  console.log(code)
                }
              })
              .catch((error) => {
                console.log(error)
              })
          } else {
            console.warn('链接失败, code:', res.code)
          }
          //   myEmit('initRongIMLib', RongIMLib) // 传递RongIMLib
        })
        .catch((err) => {
          console.log(err)
        })
    })
    .catch((err) => {
      console.log(err, 'err')
    })
}
console.log(RongIMLib, 'RongIMLib')
// 添加事件监听
const Events = RongIMLib.Events

RongIMLib.addEventListener(Events.CONNECTING, () => {
  console.log('正在链接服务器')
})

RongIMLib.addEventListener(Events.DISCONNECT, () => {
  console.log('断开链接服务器')
})
RongIMLib.addEventListener(Events.SUSPEND, () => {
  console.log('断开链接服务器')
})
RongIMLib.addEventListener(Events.CONNECTED, () => {
  console.log('已经链接到服务器')
})

const listener = (evt) => {
  // console.log(evt.messages)
  try {
    evt.messages.forEach((val) => {
      if (val.content.content) {
        // console.log(val.content.content, 'val.content.content')
        const data = JSON.parse(val.content.content) ? JSON.parse(val.content.content) : null
        // console.log(data, 'message list')
        switch (data.type?.toString()) {
          case '0':
            if (data.identity !== 3) {
              messageList.value.push(data)
              scrollToBottom()
            }
            break
          case '1':
            joinList.data = data
            break
        }
      }
      // console.log(val.content.content && JSON.parse(val.content.content), 'content')
    })
  } catch (error) {
    console.log(error, 'error')
  }
}

// 添加具体事件监听器
RongIMLib.addEventListener(Events.MESSAGES, listener)

const login = () => {
  appConfigState.LoginModalHandle(true)
  // router.push('/login')
}
const sendMsg = () => {
  if (!userState.userInfo) return
  if (!msg.value) {
    message.error('请输入内容')
    return
  }
  console.log(111, 'chat')
  const conversation = {
    conversationType: RongIMLib.ConversationType.CHATROOM,
    targetId: chatRoomIdRef.value
  }
  const data = {
    content: msg.value,
    contentColor: '',
    experienceLevel: 0,
    headUrl: undefined,
    id: '1816427620896739328',
    identity: 0,
    isLink: 0,
    nickname: userState?.userInfo?.nick ? userState?.userInfo?.nick : 'momo',
    nobleLevel: 0,
    pushTime: null,
    sign: '',
    type: 0,
    userId: 2170106,
    violationStatus: false
  }

  const messageIm = new RongIMLib.TextMessage({
    content: JSON.stringify(data)
  })

  RongIMLib.sendMessage(conversation, messageIm).then((res) => {
    console.log(res, 'sendMsg')
    if (res.code === RongIMLib.ErrorCode.SUCCESS) {
      // 消息发送成功，可以根据返回结果中的 messageId 字段将列表中的该消息状态改为发送成功。
      console.log('消息发送成功', res.data)
      const data = JSON.parse(res.data.content.content)
        ? JSON.parse(res.data.content.content)
        : null
      // console.log(data, 'message list')
      switch (data.type?.toString()) {
        case '0':
          if (data.identity !== 3) {
            messageList.value.push(data)
          }
          break
        case '1':
          joinList.data = data
          break
      }
      //   myEmit('sendMsgHandle', res.data)
    } else {
      // 消息发送失败，可以根据返回结果中的 messageId 字段将列表中的该消息状态改为发送失败。
      console.log('消息发送失败', res.code, res.msg)
    }
  })
  msg.value = ''
}

const listener2 = (event) => {
  if (event.rejoinedRoom) {
    console.log('SDK 内部重连聊天室信息:', event.rejoinedRoom)
  }
  if (event.updatedEntries) {
    console.log('监听到的聊天室 KV 更新:', event.updatedEntries)
  }
  if (event.userChange) {
    console.log('加入退出的用户通知:', event.userChange)
  }
  if (event.chatroomDestroyed) {
    console.log('聊天室销毁:', event.chatroomDestroyed)
  }
  /*  since 5.7.9 */
  if (event.chatroomNotifyMultiLoginSync) {
    console.log('加入退出多端同步通知:', event.chatroomNotifyMultiLoginSync)
  }
  /*  since 5.7.9 */
  if (event.chatroomNotifyBlock) {
    console.log('聊天室用户封禁通知:', event.chatroomNotifyBlock)
  }
  /*  since 5.7.9 */
  if (event.chatroomNotifyBan) {
    console.log('聊天室用户禁言通知:', event.chatroomNotifyBan)
  }
}
RongIMLib.addEventListener(Events.CHATROOM, listener2)
const scrollToBottom = () => {
  if (messageContainer.value) {
    console.log(messageContainer.value.scrollHeight, 'messageContainer.value ')
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}
watch(
  () => props.chatId,
  (newProps) => {
    if (chatRoomIdRef.value !== newProps) {
      chatRoomIdRef.value = newProps
      console.log(newProps)
      messageList.value = []
      initRongIMLib()
    }
  }
)
watch(
  () => userState,
  (newState) => {
    console.log(newState, 'newState')
  }
)

watch(messageList, (newData) => {
  if (newData) {
    console.log(newData, 'newData')
    nextTick(() => {
      scrollToBottom()
    })
  }
})
</script>
<style lang="scss" scoped>
.chat_container {
  height: 400px;
  //   display: flex;
  display: flex;
  flex-direction: column;
  position: relative;
  .activity {
    background-color: #e0f7e9;
    padding: 10px;
    border-radius: 10px;
    // margin: 10px 0;
    font-size: 14px;
    color: #4caf50;
    display: flex;
    align-items: center;
    img {
      width: 20px;
    }
    .txt {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .message-container {
    flex: 1;
    // height: 400px;
    overflow: scroll;
  }
  .vip-list {
    display: flex;
    flex-direction: column;
    // padding: 10px 12px;
    // overflow: scroll;
    // height: 100%;
    // flex: 1;

    .vip-item {
      // display: flex;
      // align-items: center;
      margin-bottom: 5px;
      font-weight: 400;
      font-size: 12px;
      display: flex;
      align-items: flex-start;
      .nickname {
        color: #6e94ea;
        margin-right: 4px;
      }
      .vip-badge {
        width: 52px;
        // height: 30px;
        margin-right: 10px;
        display: inline;

        object-fit: contain;
      }

      .vip-info {
        font-size: 12px;
        color: #333;
        color: rgba(82, 90, 121, 1);
        word-break: break-all;
        word-wrap: break-word;
        line-height: 20px;
      }
    }
  }

  .join-list {
    // height: 16px;
    padding: 10px 12px;
    // background: #f8faff;
    display: flex;
    .nickname {
      color: rgba(110, 148, 234, 1);
      padding-right: 6px;
    }
    .text {
      color: rgb(155, 167, 189);
    }
  }
  .comment-section {
    .comment-tools {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .tool-text {
        font-size: 14px;
        color: #4caf50;
        margin-right: 10px;
      }

      .tool-icon {
        width: 20px;
        height: 20px;
        background-color: #ccc;
        border-radius: 50%;
        margin-right: 5px;
      }
    }

    .isNotLogin {
      // width: 259px;
      flex: 1;
      height: 30px;
      padding: 0 10px;
      background: #f5f7ff;
      box-shadow: 0px 1px 0px 0px #f5f7ff;
      border-radius: 15px 15px 15px 15px;
      display: flex;
      align-items: center;
      font-weight: 400;
      font-size: 14px;
      .login_btn {
        margin-right: 6px;
        color: #67b6ff;
        cursor: pointer;
      }
    }
    .isLogin {
      display: flex;
      align-items: center;
      flex: 1;
      // .comment-input {
      //   flex: 1;
      // }
      // .send_btn {
      //   margin-left: 10px;
      //   font-size: 12px;
      //   color: #fff;
      //   // padding: 10px 20px;
      //   // background: rgba(31, 205, 44, 1);
      //   border-radius: 30px;
      //   background: url('@/assets/icons/chat-btn.webp') no-repeat;
      //   width: 66px;
      //   height: 30px;
      //   line-height: 30px;
      //   text-align: center;
      //   background-size: 100% 100%;
      // }
    }

    .comment-input {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // background-color: #fff;
      // padding: 5px;
      // border-radius: 20px;
      width: 100%;
      height: 36px;
      background: #f5f7ff;
      border-radius: 20px 20px 20px 20px;

      input {
        flex: 1;
        border: none;
        padding: 5px 10px;
        border-radius: 20px;
        outline: none;
        background: transparent;
      }

      .send-button {
        background-color: #4caf50;
        color: white;
        border: none;
        border-radius: 0 20px 20px 0;
        padding: 5px 15px;
        // margin-left: 10px;
        cursor: pointer;
      }
    }
  }
}
</style>
